package com.infolab.aims.web;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.infolab.aims.common.AbstractController;
import com.infolab.aims.common.CommonUtil;


@Controller
@RequestMapping("/log")
public class LogController extends AbstractController {
	
	public static final String CONTEXT_PATH ="/log";
	public static final String JSP_MAIN_FORM="logSearch";
	public static final String JSP_LOG_VIEW="logView";
	
	@Value("${logFolder}")
	private String LOG_FOLDER = "c:\\";
	
	Log logger = LogFactory.getLog(getClass());

	@RequestMapping(value="search", method = RequestMethod.GET)
	public String createSystemCodeType(Model model) {
		File folder = new File(LOG_FOLDER);
		if(folder != null && folder.isDirectory()){
			List<File> file = Arrays.asList(folder.listFiles()); //(List<File>)FileUtils.listFiles(folder, null, false);
			model.addAttribute("fileList", file);
		}
		return JSP_MAIN_FORM;
	}
	
	
	@RequestMapping(value={"detail"}, method = RequestMethod.GET)
	public void createFaultCode(@RequestParam(required=false,value="filename") String filename,Model model,HttpServletResponse resp) {
		File file = new File(LOG_FOLDER + filename);
		if(file.exists() && file.isFile()){
			try {
				resp.setHeader("Content-Disposition", "attachment; filename="+file);
				String logs = FileUtils.readFileToString(file);
				resp.getWriter().write(logs);
				resp.getWriter().flush();
				//model.addAttribute("fileContent", list);
			} catch (IOException e) {
				logger.error(CommonUtil.getStackTrace(e));
			}
		}
	}
	
	
}
